# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import commonlib
import datetime
import time
import simplejson as json
import traceback
import wlive_feed
import threading
import logging
matchQueue = {}

logging.basicConfig()
logger = logging.getLogger('wlive_7m')
logger.setLevel(logging.DEBUG)
class Wlive():
    listGiaiDau = {'ENG PR': 'Anh', 'SPA D1': 'Tây Ban Nha', 'UEFA CL': 'Champions League'}
    
    def __init__(self):
        self.__matches = {}
    
    def getListMatch(self):
        url = 'http://wlive.7m.cn/gamedata/vn/{0}.js?nocache={1}'.format(datetime.datetime.now().strftime("%Y%m"), time.time())
        logger.debug(unicode('Call getListMatchOfDay(url={0})'.format(url), 'utf8'))
        now = datetime.datetime.utcnow()
        try:
            html = commonlib.getHTML(url, headers={'X-Requested-With': 'XMLHttpRequest'}, delay=2, max_retries=3)
            jdata = json.loads(html)
            for match in jdata:
                mid = match['oid']
                if not match['matchNameShort'] in self.listGiaiDau.keys(): continue
                match['giaidau'] = Wlive.listGiaiDau.get(match['matchNameShort'], '')
                match['dategmt7'] = datetime.datetime.fromtimestamp(match['date']/1000)
                match['date'] = datetime.datetime.fromtimestamp(match['date'] / 1000) + datetime.timedelta(seconds=time.timezone)
                if ((now.month == match['date'].month) and (now.day == match['date'].day)): 
                  if now.hour > match['date'].hour + 3: continue
                  self.__matches[mid] = match
        except:
            logger.error(traceback.format_exc())
        logger.debug(unicode('Finished getListMatchOfDay(url={0})'.format(url), 'utf8'))
    
    def run(self):
        while True:
            if len(self.__matches) == 0: self.getListMatch()
            logger.info(unicode('có {0} trận diễn ra hôm nay'.format(len(self.__matches.keys())), 'utf8'))
            if len(self.__matches) > 0:
                for match in self.__matches.values():
                    id = hash(str(match))
                    if matchQueue.has_key(id):
                        if (not matchQueue[id].isAlive()): 
                            del matchQueue[id]
                        else:
                            logger.debug('thread feeding match between {0} still alive'.format(matchQueue[id].getName()))
                    if id not in matchQueue.keys():
                        matchQueue[id] = wlive_feed.GetFeed(match)
                        matchQueue[id].start()
                logger.info('main thread sleep 1800s')
            time.sleep(1800)
    
    
class UpdateMatchesTimer(threading.Thread):
    
    def __init__(self, interval, function):
        threading.Thread.__init__(self)
        self.__interval = interval
        self.__function = function

    def run(self):
        while True:
            time.sleep(self.__interval)
            logger.debug('call updateMatchesTimer')
            if type(self.__function).__name__ == 'instancemethod':
                self.__function() 
            else:
                self.__function

if __name__ == '__main__':
    bd = Wlive()
    UpdateMatchesTimer(3600, bd.getListMatch).start()
    bd.run()
    
